<template>
<!-- 给item每一项添加动画 -->
  <transition name="todo" appear>
  <li>
      <label>
        <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
        <span v-show="!todo.isEdit">{{todo.title}}</span>
        <input type="text" 
        v-show="todo.isEdit" 
        :value="todo.title" 
        @blur="handleBlur(todo,$event)"
        ref="inputUpdate">
      </label>
      <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
      <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
  </li>
  </transition>
</template>

<script>
export default {
  name:'MyItem',
  props:["todo","checkTodo","handleTodo"],
  methods:{
    handleCheck(id){
      // 通知App数据更新
      // 数据在哪里，方法就写在哪里
      this.checkTodo(id)
    },
    handleDelete(id){
      // 通知App删除item
      this.handleTodo(id)
    },
    // 编辑
    handleEdit(todo){
      if(Object.prototype.hasOwnProperty.call(todo,'isEdit')){
        todo.isEdit=true
      }
      else{
        // 没有这个属性就要响应式设置
        this.$set(todo,'isEdit',true)
      }
        // nextTick属性在数据改变后下次基于新的dom去操作
        this.$nextTick(function(){
          this.$refs.inputUpdate.focus()
        })
        // setTimeout(() => {
        //             this.$refs.inputUpdate.focus()
        // });
    },
    // 失去焦点
    handleBlur(todo,e){
      todo.isEdit=false
      // 失去焦点执行的逻辑
      if(!e.target.value.trim()) return
      this.$bus.$emit('updateTodo',todo.id,e.target.value)
    }
  }
}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover{
  background-color: #ddd;
}
li:hover button{
  display: block;
}
/* 动画效果 */
.todo-enter-active{
  animation: donghua .5s linear;
}
.todo-leave-active{
  animation: donghua .5s linear reverse;
}
@keyframes donghua {
  from{
    transform: translateX(100%);
  }
  to{
    transform: translateX(0);
  }
  
}
</style>